
<template>
  <view class="uni-container">
    <uni-forms ref="form" v-model="formData" validateTrigger="bind">
			<uni-forms-item name="student" label="学生">
				<el-cascader :props="lazyStudent" multiple="true"  v-model="formData.student" style="width: 300px;"></el-cascader>
			</uni-forms-item>
			<uni-forms-item name="tclass_id"  
				v-for="(key,index) in formData.tclass_id" 
				:label="'教学班'+(index+1)"
				:key="key.key"
				:prop="'tclass_id.' + index + '.value'"
			>
			<view style="display: flex;flex-direction: row;">
				<el-cascader :props="lazyProps"  v-model="key.value" style="width: 300px;"></el-cascader>
				<button class="uni-button" style="width: 80px; margin-left: 10px;" type="warn" @click="delClass(key)">删除</button>
			</view>
			</uni-forms-item>
			<view class="uni-button-group" style="margin-bottom: 40rpx;">
				<button class="uni-button"  style="width: 100px;" @click="addClass">新增</button>
			</view>
			<uni-forms-item name="credit" label="总学分">
				<uni-easyinput placeholder="总学分" type="number" v-model="formData.credit" />
			</uni-forms-item>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/student/schedule/list" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import validator from '@/js_sdk/validator/user-schedule.js';
	import Vue from 'vue'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'hr-userSchedule';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
				lazyStudent:{
					lazy : true,
					multiple: true,
					lazyLoad : (node , resolve) => {
						if(node.level == 3) return resolve([])
						const {level , data} = node , params = [{},{college: data && data.value},{ where : data && data.value }][level], load = [this.loadCollege,this.loadGrade,this.loadStudent][level]
						// async load
						load(params).then(r=>{
							resolve(r.map(({id , name}) => {
								return {value : id , label : name , leaf : level >= 2}
							}))
						}).catch(()=>{
							resolve()
						})
					}
				},
				lazyProps:{
					lazy : true,
					lazyLoad : (node , resolve) => {
						if(node.level == 3) return resolve([])
						const {level , data} = node , params = [{},{college: data && data.value},{ course : data && data.value }][level], load = [this.loadCollege,this.loadCourse,this.loadClass][level]
						// async load
						load(params).then(r=>{
							resolve(r.map(({id , name}) => {
								return {value : id , label : name , leaf : level >= 2}
							}))
						}).catch(()=>{
							resolve()
						})
					}
				},
        formData: {
					"tclass_id": [{value: '',key: Date.now()}],
					"credit": 38,
					"student":[]
				},
      }
    },
		
    methods: {
			/**
			 * 删除教学班列
			 */
			delClass(item){
				var index = this.formData.tclass_id.indexOf(item)
				if (index !== -1) {
					this.formData.tclass_id.splice(index, 1)
				}
			},
			
			/**
			 * 添加教学班列
			 */
			addClass(){
				this.formData.tclass_id.push({
					value: '',
					key: Date.now()
				});
			},
			
			/**
			 * 异步加载学院信息
			 * @param {Object} value
			 */
			loadCollege(params){
				return new Promise(function(resolve , reject){
					db.collection('hr-college')
						.where(params)
						.get().then((res)=>{
							let {affectedDocs , data} = res.result
							if(affectedDocs == 0){
								reject()
							}else{
								let result = data.map(({college_id:id,name:name})=>{
									return {id,name}
								})
								resolve(result);
							}
					})
				})
			},
			
			/**
			 * 异步加载课程信息
			 * @param {Object} value
			 */
			loadCourse(params){
				return new Promise(function(resolve , reject){
						db.collection('hr-course')
						.where(params)
						.get().then((res)=>{
							let {affectedDocs , data} = res.result
							if(affectedDocs == 0){
								reject()
							}else{
								let result = data.map((detail)=>{
									let {course_id:id,course_name,credit} = detail
									let name = `${course_name} - ${credit}学分`
									return {id,name,credit}
								})
								resolve(result);
							}
						})
				})
			},
			
			/**
			 * 异步加载班级信息
			 * @param {Object} value
			 */
			loadClass(params){
				const character = ['周一', '周二', '周三', '周四', '周五'];
				const time = ['09:00-10:20', '10:40-12:00', '12:30-13:50', '14:00-15:20', '15:30-16:50', '17:00-18:20','19:00-20:20','20:30-21:50'];
				Object.assign(params,{ optionalNumber:dbCmd.gt(0) })
				return new Promise(function(resolve , reject){
					db.collection('teaching-class')
					.where(params)
					.get().then((res)=>{
						let {affectedDocs , data} = res.result
						if(affectedDocs == 0){
							reject()
						}else{
							let result = data.map((detail)=>{
								let {class_id , day , node} = detail
								let id = class_id , name =  `${class_id}  ${character[day]}-${time[node]}`
								return {id,name}
							})
							resolve(result);
						}
					})
				}) 
			},
			
			/**
			 * 加载年级信息
			 * @param {Object} value
			 */
			loadGrade(params){
				let { college } = params
				return new Promise(function(resolve , reject){
				let nowYear = new Date().getFullYear()
				let res = [{"id": {college,year:nowYear+""},"name": nowYear},{"id": {college,year:nowYear-1+""},"name": nowYear-1},{"id": {college,year:nowYear-2+""},"name": nowYear-2},{"id": {college,year:nowYear-3+""},"name": nowYear-3},{"id": {college,year:nowYear-4+""},"name": nowYear-4}]
				resolve(res.reverse()) 
				})
			},
			
			/**
			 * 加载年级信息
			 * @param {Object} value
			 */
			loadStudent(params){
				let { where } = params
				where.role = 'STUDENT'
				return new Promise( async (resolve , reject) => {
					await this.$request('schedule/loadStudent',where).then((data)=>{
						let res = data.map((item)=>{
							let {username , nickname} = item
							let name =  `${username}-${nickname}`
							return {id:username,name}
						})
						resolve(res)
					})
				}) 
			},
		
			
			/**
			 * 触发表单提交
			 */
			submit() {
			  uni.showLoading({
					title: '提交中',
			    mask: true
			  })
			  this.$refs.form.submit().then((res) => {
			    this.submitForm(res).then((data)=>{
						let sucCount = 0 , failCount = 0 , failMessage = ''
						data.map((item , index)=>{
							item.code == 0 ? sucCount++ : failCount++
						})
						console.log(sucCount,failCount)
						uni.showModal({
							showCancel:false,
						    title: '提示',
						    content: `成功有：${sucCount},失败有：${failCount}\n 失败的条数在`,
						    success: function (res) {
									setTimeout(() => uni.navigateTo({
										url: '/pages/system/user/list'
									}), 1000)
								}
						});
						uni.hideLoading()
					}).catch((errors) => {
						uni.hideLoading()
					})
			  }).catch((errors) => {
			    uni.hideLoading()
			  })
			},

      submitForm(value) {
			 let {student} = value , len = student.length , result = []
			 return new Promise((res,rej)=>{
				 let count = 1
				 function isEnd(){
					 if(count == len){
						 res(result)
					 }
					 count++
				 }
				 // 每个学生分别选课
				 student.map((item)=>{
				 		console.log(item)
						this.selectionCourse(item[2]).then((res)=>{
							console.log(res)
							result.push(res)
							isEnd()
						})
				 })
			 })
      },
	
				// userSchedule = {
				// 	username, 学号
				// 	tclass_id, 教学班id列表
				//  credit,    总学分
				// 	usedcredit, 可选学分
				// 	schedule, 课程表
				// 	year, 年份
				// 	term, 学期
				// }
				// year 当前年份 term 学期
			async selectionCourse(username){
				const year = new Date().getFullYear() , term = new Date().getMonth()+1 < 6 ? 0 : 1 
				let {tclass_id,credit} = this.formData , userSchedule = {username , year , term ,tclass_id ,credit}

				let course = tclass_id
				if(!this.empty(course[0])){
					await this.$request('course/selectionCourse',{username,course,credit}).then((res)=>{
						let {usedCredits , result} = res.data
						userSchedule.usedcredit = usedCredits
						userSchedule.schedule  = result
					})
				}else{
					userSchedule.usedcredit = 0
					userSchedule.schedule  = []
				}
			 // 使用 uni-clientDB 提交数据
			 return await db.collection(dbCollectionName).add(userSchedule).then((res) => {
				 return { code:0 }
			 }).catch((err) => {
				 return {
					 code: 10001,
					 err:err
				 }
			 })
			}
    }
  }
</script>

